﻿using System;
using System.Collections.Generic;

using System.Text;

namespace RoughJs.Ast
{
    /// <summary>
    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
    /// 
    /// 这个实现了本地对象
    /// 
    /// 参看ECMA 15.2.
    /// </summary>
    public class NativeObject : IdScriptableObject
    {
        private static Object OBJECT_TAG = "Object";
        private const int
        Id_constructor = 1,
        Id_toString = 2,
        Id_toLocaleString = 3,
        Id_valueOf = 4,
        Id_hasOwnProperty = 5,
        Id_propertyIsEnumerable = 6,
        Id_isPrototypeOf = 7,
        Id_toSource = 8,
        Id___defineGetter__ = 9,
        Id___defineSetter__ = 10,
        Id___lookupGetter__ = 11,
        Id___lookupSetter__ = 12,
        MAX_PROTOTYPE_ID = 12;
        public static void init(Scriptable scope, bool sealed1)
        {
            NativeObject obj = new NativeObject();
            obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed1);
        }
        public override string getClassName()
        {
            return "Object";
        }
        public override string ToString()
        {
            return ScriptRuntime.defaultObjectToString(this);
        }
        public override int findPrototypeId(string s)
        {
            int id;
// #generated# Last update: 2007-05-09 08:15:55 EDT
        id = 0; String X = null; int c;
             switch (s.Length) {
            case 7: X="valueOf";id=Id_valueOf; goto L;
            case 8: c=s.ToCharArray()[3];
                if (c=='o') { X="toSource";id=Id_toSource; }
                else if (c=='t') { X="toString";id=Id_toString; }
                goto L;
            case 11: X="constructor";id=Id_constructor; goto L;
            case 13: X="isPrototypeOf";id=Id_isPrototypeOf; goto L;
            case 14: c = s.ToCharArray()[0];
                if (c=='h') { X="hasOwnProperty";id=Id_hasOwnProperty; }
                else if (c=='t') { X="toLocaleString";id=Id_toLocaleString; }
                goto L;
            case 16: c=s.ToCharArray()[2];
                if (c=='d') {
                    c=s.ToCharArray()[8];
                    if (c=='G') { X="__defineGetter__";id=Id___defineGetter__; }
                    else if (c=='S') { X="__defineSetter__";id=Id___defineSetter__; }
                }
                else if (c=='l') {
                    c=s.ToCharArray()[8];
                    if (c=='G') { X="__lookupGetter__";id=Id___lookupGetter__; }
                    else if (c=='S') { X="__lookupSetter__";id=Id___lookupSetter__; }
                }
                goto L;
            case 20: X="propertyIsEnumerable";id=Id_propertyIsEnumerable; goto L;
            }
            L:;
            if  (X!=null && X!=s && !(X==s)) id = 0;
            goto L0;
        
            L0: ;
// #/generated#
        return id;
        }
        public override void initPrototypeId(int id)
        {
            String s;
            int arity;
            switch (id)
            {
                case Id_constructor: arity = 1; s = "constructor"; break;
                case Id_toString: arity = 0; s = "toString"; break;
                case Id_toLocaleString: arity = 0; s = "toLocaleString"; break;
                case Id_valueOf: arity = 0; s = "valueOf"; break;
                case Id_hasOwnProperty: arity = 1; s = "hasOwnProperty"; break;
                case Id_propertyIsEnumerable:
                    arity = 1; s = "propertyIsEnumerable"; break;
                case Id_isPrototypeOf: arity = 1; s = "isPrototypeOf"; break;
                case Id_toSource: arity = 0; s = "toSource"; break;
                case Id___defineGetter__:
                    arity = 2; s = "__defineGetter__"; break;
                case Id___defineSetter__:
                    arity = 2; s = "__defineSetter__"; break;
                case Id___lookupGetter__:
                    arity = 1; s = "__lookupGetter__"; break;
                case Id___lookupSetter__:
                    arity = 1; s = "__lookupSetter__"; break;
                default: throw new ArgumentException(id.ToString());
            }
            initPrototypeMethod(OBJECT_TAG, id, s, arity);
        }
        public override object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, object[] args)
        {
            if (!f.hasTag(OBJECT_TAG))
            {
                return base.execIdCall(f, cx, scope, thisObj, args);
            }
            int id = f.methodId();
            switch (id)
            {
                case Id_constructor:
                    {
                        if (thisObj != null)
                        {
                            // BaseFunction.construct will set up parent, proto
                            return f.construct(cx, scope, args);
                        }
                        if (args.Length == 0 || args[0] == null
                            || args[0] == Undefined.instance)
                        {
                            return new NativeObject();
                        }
                        return ScriptRuntime.toObject(cx, scope, args[0]);
                    }

                case Id_toLocaleString: // For now just alias toString
                case Id_toString:
                    {
                        if (cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE))
                        {
                            String s = ScriptRuntime.defaultObjectToSource(cx, scope,
                                                                           thisObj, args);
                            int L = s.Length;
                            if (L != 0 && s.ToCharArray()[0] == '(' && s.ToCharArray()[L - 1] == ')')
                            {
                                // Strip () that surrounds toSource
                                s = s.Substring(1, L - 1);
                            }
                            return s;
                        }
                        return ScriptRuntime.defaultObjectToString(thisObj);
                    }

                case Id_valueOf:
                    return thisObj;

                case Id_hasOwnProperty:
                    {
                        bool result;
                        if (args.Length == 0)
                        {
                            result = false;
                        }
                        else
                        {
                            String s = ScriptRuntime.toStringIdOrIndex(cx, args[0]);
                            if (s == null)
                            {
                                int index = ScriptRuntime.lastIndexResult(cx);
                                result = thisObj.has(index, thisObj);
                            }
                            else
                            {
                                result = thisObj.has(s, thisObj);
                            }
                        }
                        return ScriptRuntime.wrapBoolean(result);
                    }

                case Id_propertyIsEnumerable:
                    {
                        bool result;
                        if (args.Length == 0)
                        {
                            result = false;
                        }
                        else
                        {
                            String s = ScriptRuntime.toStringIdOrIndex(cx, args[0]);
                            if (s == null)
                            {
                                int index = ScriptRuntime.lastIndexResult(cx);
                                result = thisObj.has(index, thisObj);
                                if (result && thisObj is ScriptableObject)
                                {
                                    ScriptableObject so = (ScriptableObject)thisObj;
                                    int attrs = so.getAttributes(index);
                                    result = ((attrs & ScriptableObject.DONTENUM) == 0);
                                }
                            }
                            else
                            {
                                result = thisObj.has(s, thisObj);
                                if (result && thisObj is ScriptableObject)
                                {
                                    ScriptableObject so = (ScriptableObject)thisObj;
                                    int attrs = so.getAttributes(s);
                                    result = ((attrs & ScriptableObject.DONTENUM) == 0);
                                }
                            }
                        }
                        return ScriptRuntime.wrapBoolean(result);
                    }

                case Id_isPrototypeOf:
                    {
                        bool result = false;
                        if (args.Length != 0 && args[0] is Scriptable)
                        {
                            Scriptable v = (Scriptable)args[0];
                            do
                            {
                                v = v.getPrototype();
                                if (v == thisObj)
                                {
                                    result = true;
                                    break;
                                }
                            } while (v != null);
                        }
                        return ScriptRuntime.wrapBoolean(result);
                    }

                case Id_toSource:
                    return ScriptRuntime.defaultObjectToSource(cx, scope, thisObj,
                                                               args);
                case Id___defineGetter__:
                case Id___defineSetter__:
                    {
                        if (args.Length < 2 || !(args[1] is Callable))
                        {
                            Object badArg = (args.Length >= 2 ? args[1]
                                             : Undefined.instance);
                            throw ScriptRuntime.notFunctionError(badArg);
                        }
                        if (!(thisObj is ScriptableObject))
                        {
                            throw Context.reportRuntimeError2(
                                "msg.extend.scriptable",
                                thisObj.GetType().Name,
                                Convert.ToString(args[0]));
                        }
                        ScriptableObject so = (ScriptableObject)thisObj;
                        String name = ScriptRuntime.toStringIdOrIndex(cx, args[0]);
                        int index = (name != null ? 0
                                     : ScriptRuntime.lastIndexResult(cx));
                        Callable getterOrSetter = (Callable)args[1];
                        bool isSetter = (id == Id___defineSetter__);
                        so.setGetterOrSetter(name, index, getterOrSetter, isSetter);
                        if (so is NativeArray)
                            ((NativeArray)so).setDenseOnly(false);
                    }
                    return Undefined.instance;

                case Id___lookupGetter__:
                case Id___lookupSetter__:
                    {
                        if (args.Length < 1 ||
                            !(thisObj is ScriptableObject))
                            return Undefined.instance;

                        ScriptableObject so = (ScriptableObject)thisObj;
                        String name = ScriptRuntime.toStringIdOrIndex(cx, args[0]);
                        int index = (name != null ? 0
                                     : ScriptRuntime.lastIndexResult(cx));
                        bool isSetter = (id == Id___lookupSetter__);
                        Object gs;
                        for (; ; )
                        {
                            gs = so.getGetterOrSetter(name, index, isSetter);
                            if (gs != null)
                                break;
                            // If there is no getter or setter for the object itself,
                            // how about the prototype?
                            Scriptable v = so.getPrototype();
                            if (v == null)
                                break;
                            if (v is ScriptableObject)
                                so = (ScriptableObject)v;
                            else
                                break;
                        }
                        if (gs != null)
                            return gs;
                    }
                    return Undefined.instance;

                default:
                    throw new ArgumentException(id.ToString());
            }
        }

    }
}
